package filters

import (
	"api/types"
	"github.com/valyala/fasthttp"
	"strings"
	"net/http"
	"github.com/funlake/gopkg/utils"
	"os"
	"api/conf"
)

func NewFilterInit() *FilterInit {
	return &FilterInit{}
}
type FilterInit struct{

}

func (fa *FilterInit) Pre(proxyContext *types.ProxyContext,fasthttpCtx *fasthttp.RequestCtx)(bool,int,string){
	serviceUrl := proxyContext.Scheme+"://"+ proxyContext.Vhost+ proxyContext.Domain+"/"+ proxyContext.Service
	qs := proxyContext.QueryString
	//copy query string
	if strings.Contains(qs,"?") {
		qss := strings.Split(qs, "?")
		if len(qss) > 1 {
			serviceUrl = serviceUrl + "?" + qss[1]
		}
	}
	var err error
	proxyContext.Req,err = http.NewRequest(proxyContext.Method, serviceUrl , strings.NewReader(utils.ByteToStr(proxyContext.PostData)))
	if err != nil{
		return false,conf.REQUEST_MERGE_PARSE_ERROR,err.Error()
	}
	proxyContext.Header.VisitAll(func(key, value []byte) {
		val :=  utils.ByteToStr(value)
		//验证header值是否legal,否则会导致请求panic
		if validHeaderFieldValue(val){
			proxyContext.Req.Header.Set(utils.ByteToStr(key),val)
		}
	})
	//request包请求会自带压缩头，这里不设置，则proxy返回将是压缩后的http body
	proxyContext.Req.Header.Set("Accept-Encoding","")
	cipher := os.Getenv("GATEWAY_CIPHER")
	if cipher == ""{
		cipher = "g-w2&d0yx1j7"
	}
	proxyContext.Req.Header.Set("Etccb-Gwcipher",cipher)
	return true,0,""
}
func (fa *FilterInit) Post(proxyContext *types.ProxyContext,fasthttpCtx *fasthttp.RequestCtx)(bool,int,string){
	return true,0,""
}

func validHeaderFieldValue(v string) bool {
	for i := 0; i < len(v); i++ {
		b := v[i]
		if isCTL(b) && !isLWS(b) {
			return false
		}
	}
	return true
}

func isCTL(b byte) bool {
	const del = 0x7f // a CTL
	return b < ' ' || b == del
}

func isLWS(b byte) bool { return b == ' ' || b == '\t' }